package com.atguigu.srb.core.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.srb.core.mapper.DictMapper;
import com.atguigu.srb.core.pojo.dto.ExcelDictDTO;
import com.atguigu.srb.core.pojo.entity.Dict;
import com.atguigu.srb.core.service.DictService;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@NoArgsConstructor
public class ExcelDictDTOListener extends AnalysisEventListener<ExcelDictDTO> {

    //设置批处理的长度大小
    private static final int BATCH_COUNT = 5;

    List<ExcelDictDTO> dtoList = new ArrayList<>();

    private DictMapper dictMapper;

    public ExcelDictDTOListener(DictMapper dictMapper){
        this.dictMapper = dictMapper;
    }

    @Override
    public void invoke(ExcelDictDTO data, AnalysisContext context) {
        log.info("字典数据导入....");
        dtoList.add(data);
        if(dtoList.size()>5){
            //保存数据
            this.saveBatch();
            //清空数据
            dtoList.clear();
        }
    }

    private void saveBatch() {
        log.info("保存{}条数据",dtoList.size());
        dictMapper.insertBatch(dtoList);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveBatch();
        log.info("数据导入成功。。。。。");
    }
}
